
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.forms.OrdersForm;
import com.scalar.chiptrack.users.User;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.6 $ $Date: 2011/03/21 16:39:40 $
 */

public final class PendingOrdersAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/pendingOrders.do";  // Added by Basha (08/08/2003)

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        ArrayList pendingList = new ArrayList ();
        OrdersForm subform  = ( OrdersForm ) form;
        String action       = request.getParameter ( "action" );
        String isSampleStr  = request.getParameter ( "isSample" );
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + "isSample="+request.getParameter("isSample"));
            return ( mapping.findForward ( "login" ) );
        }
        HashMap errors = new HashMap ();
        HashMap info   = new HashMap();
        if ( action == null )
        {
            request.setAttribute ( "showList", "FALSE" ); //Not to show the list by default
        }
        int isSample = 1; //default set to salesOrder
        if ( isSampleStr != null && !isSampleStr.equals ( "null" ) )
        {
            try
            {
                isSample = Integer.parseInt ( isSampleStr );
            }
            catch ( NumberFormatException ignore ) { isSample = 1; }
        }

        if ( "searchAllPendingOrders".equals ( action ) )
        {
            request.setAttribute ( "showList", "TRUE" );
            int orderType = 1;
            if( request.getParameter( "isSample" ) != null )
            {
            	orderType = Integer.parseInt( request.getParameter( "isSample" ) );
            }
            pendingList = SalesDAO.loadPendingOrdersToApprove ( "0", "0", "", orderType, ( Calendar.getInstance ().get ( Calendar.YEAR ) ), "", "0","0" );
            if ( pendingList.size () == 0 )
            {
                errors.put ( ERROR_PENDING_SALES_ORDER_NOT_FOUND, null );
                request.setAttribute ( "showList", "FALSE" );
            }
            else
            {
                //Show the pendingList only when it searched
                request.setAttribute ( "showList", "TRUE" );
            }
            request.setAttribute ( "ordersForm", null );
        }
        if ( "SearchOrder".equals ( action ) )
        {
            String customerId           = ( String ) BeanUtils.getSimpleProperty ( form, "customerId" );
            String manufacturingPartNo  = request.getParameter ( "manufacturingPartNo" );
            String fromDate             = ( String ) BeanUtils.getSimpleProperty ( form, "fromDate" );
            String toDate               = ( String ) BeanUtils.getSimpleProperty ( form, "toDate" );
            String salesOrderId         = ( String ) BeanUtils.getSimpleProperty ( form, "salesOrderId" );
            String customerPO           = ( String ) BeanUtils.getSimpleProperty ( form, "customerPO" );
            String endCustomer =  ( String ) BeanUtils.getSimpleProperty ( form, "endCustomer" );
            String endUser =  ( String ) BeanUtils.getSimpleProperty ( form, "endUser" );
            int year = 0;
            String bookingYear = request.getParameter ( "year" );

            if ( ( bookingYear != null ) && ( bookingYear.trim ().length () != 0 ) )
            {
                try
                {
                    year = Integer.parseInt ( bookingYear );
                }
                catch ( NumberFormatException nfe )
                {
                    year = 0;
                }
            }
            if ( isSampleStr != null && !isSampleStr.equals ( "null" ) )
            {
                try
                {
                    isSample = Integer.parseInt ( isSampleStr );
                }
                catch ( NumberFormatException nfe )
                {
                    nfe.printStackTrace();
                    errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_GETTING_DATA );
                    errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Load Data " );
                    session.setAttribute ( SessionKeys.ERROR_REPORT, nfe );
                }
            }
            pendingList = SalesDAO.loadPendingOrdersToApprove ( salesOrderId, customerId, manufacturingPartNo, isSample, year, customerPO, endCustomer, endUser );
            if ( pendingList.size () == 0 )
            {
                errors.put ( ERROR_PENDING_SALES_ORDER_NOT_FOUND, null );
                request.setAttribute ( "showList", "FALSE" );
            }
            else
            {
                //Show the pendingList only when it searched
                request.setAttribute ( "showList", "TRUE" );
            }
        }

        try
        {
            request.setAttribute ( "customerList", CustomerDAO.getAllCustomerNames (isSample) );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "pendingList", pendingList );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(isSample, "PendingSalesOrders" ));
            request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(isSample, "PendingSalesOrders"));
            request.setAttribute ( "endCustomerList", NewCustomerDAO.loadAllEndCustomersWithSOEndcustomersByUserType(null,-1,false,user) );
            request.setAttribute ( "endUserList", NewCustomerDAO.loadAllEndUsersByUserType(null,-1, false,user) );
        }
        catch (Exception e)
        {                                                                                                 
            errors.put( "Error while loading the Sales orders Data", null );
        }
        if ( !errors.isEmpty () )
        {
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        }
        if ( !info.isEmpty () )
        {
            request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        }
        return ( mapping.findForward ( "success" ) );

    }

    public static ArrayList loadManufacturingProducts( int isSample ) throws Exception
    {
        ArrayList parts = new ArrayList ();
        Iterator list   = null;
        if( isSample == 0 )
        {
            list = FinishedGoodsDAO.loadFinishedGoods().iterator ();
        }
        else
        {
            list = FinishedGoodsDAO.loadAllFinishedGoods().iterator ();
        }
        parts.add ( new org.apache.struts.util.LabelValueBean ( "All Products", "" ) );
        while ( list.hasNext () )
        {
            FinishedGoods product = ( FinishedGoods ) list.next ();
            //It is better to replace with product Id here, instead of again searching the database with marketingpart no for productid
            //But i am leaving the other code as it is because we need to change lot of the code in the salesDAO. ;)
            parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), product.getManufacturingPartNo () ) );
        }

        return parts;
    }


}
